########################
# Setup

setup-reference-implementation-install-dependencies:
	cd apps/api && npm i

setup-reference-implementation-nitro-prepare:
	cd apps/api && npm run prepare

setup-reference-implementation-db-generate:
	cd apps/api/server && npm run db:generate

setup-reference-implementation:
	make setup-reference-implementation-install-dependencies
	echo -e '\n\033[0;32m    INSTALLED DEPENDENCIES\033[0m\n'
	make setup-reference-implementation-nitro-prepare
	echo -e '\n\033[0;32m    PREPARED NITRO\033[0m\n'
	make setup-reference-implementation-db-generate
	echo -e '\n\033[0;32m    GENERATED PRISMA\033[0m\n'

########################
# Run

run-reference-implementation-for-postman:  # WARNING clearly not production ready
	JWT_SECRET=dxLmhnE0pRY2+vUlu+i5Pxh8LTxLBTgBWdp82W74mMs= npm -C apps/api run dev

########################
# Tests

test-reference-implementation-with-postman-and-already-launched-server:
	DELAY_REQUEST=50 APIURL=http://localhost:3000/api api/run-api-tests.sh

test-reference-implementation-with-postman:
	@set -e; \
	JWT_SECRET=dxLmhnE0pRY2+vUlu+i5Pxh8LTxLBTgBWdp82W74mMs= npm -C apps/api run dev & \
	SERVER_PID=$$!; \
	trap "kill $$SERVER_PID 2>/dev/null || true" EXIT; \
	sleep 0.3; \
	kill -0 "$$SERVER_PID" 2>/dev/null || exit 4; \
	make test-reference-implementation-with-postman-and-already-launched-server && ( \
		make clean-running-processes; echo -e '\n\033[0;32m    TESTS OK\033[0m\n' && exit 0 \
	) || ( \
		make clean-running-processes; echo -e '\n\033[0;31m    TESTS FAILED\033[0m\n' && exit 1 \
	)

########################
# Cleaning

clean-running-processes:  # killing the parent is usually not enough, we should kill throught this helper
	ps a -A -o pid,cmd \
	| grep "$$(pwd)/apps/api/node_modules/.bin/nitro dev" \
	| cut -d" " -f1 \
	| xargs -I {} kill -9 {} \
	|| true

clean-all-non-default-files:
	rm -rf apps/api/node_modules  # npm modules - includes some files generated by prisma -> node_modules/@prisma/client
	rm -f appd/api/prisma/dev.db  # dev database
